package day3;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//公平锁和非公平锁
public class Demo3{
    //有参构造: true 表示公平锁 false(默认值) 非公平锁
    ReentrantLock lock=new ReentrantLock(true);
    //读写锁 也是类似于 : true / false
    ReentrantReadWriteLock lock2=new ReentrantReadWriteLock();
    public void test(){
        String name= null;
        try {
            name = Thread.currentThread().getName();
            lock.lock();
            System.out.println(name+"获取了锁,开始执行...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(name+"执行结束了,开始释放...");
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        Demo3 d=new Demo3();
        for(int i=0;i<5;i++){
            new Thread(()->{
                while(true) d.test();
            },"线程:"+i).start();
        }
    }
}
